package tk.mybatis.springboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import tk.mybatis.springboot.common.BaseResponse;
import tk.mybatis.springboot.common.ErrorEnum;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 */
@Controller
@EnableWebMvc
@ControllerAdvice
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(Application.class);


    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("服务启动完成!");
    }


    /**
     * 统一mvc层异常处理
     *
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseResponse jsonErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException c = (MethodArgumentNotValidException) e;
            return BaseResponse.error(ErrorEnum.PARAM_INVALIDATE,validErrors(c.getBindingResult().getAllErrors()));
        }
        logger.error(req.getRequestURI(), e);
        return BaseResponse.error(ErrorEnum.SERVICE_EXCEPTION);
    }

    /**
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ResponseBody
    String _index() {
        return "Success，Let's enjoy！";
    }

    private List<String> validErrors(List<ObjectError> objectErrors){
        List<String> errors = new ArrayList<String>(objectErrors.size());
        for(ObjectError objectError : objectErrors){
            errors.add(objectError.getDefaultMessage());
        }
        return errors;
    }
}
